iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
1
自我挑戰組

今年我想陪著 30 天系列 第 6

今年我想陪著 30 天之 6

  • 分享至 

  • xImage
  •  

1342. Number of Steps to Reduce a Number to Zero

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

  • Example 1:
    Input: num = 14
    Output: 6
    Explanation:
    Step 1) 14 is even; divide by 2 and obtain 7.
    Step 2) 7 is odd; subtract 1 and obtain 6.
    Step 3) 6 is even; divide by 2 and obtain 3.
    Step 4) 3 is odd; subtract 1 and obtain 2.
    Step 5) 2 is even; divide by 2 and obtain 1.
    Step 6) 1 is odd; subtract 1 and obtain 0.

  • Example 2:
    Input: num = 8
    Output: 4
    Explanation:
    Step 1) 8 is even; divide by 2 and obtain 4.
    Step 2) 4 is even; divide by 2 and obtain 2.
    Step 3) 2 is even; divide by 2 and obtain 1.
    Step 4) 1 is odd; subtract 1 and obtain 0.

由題意及範例可知,需要提供一個函式,此函式的參數為一個非負的整數,當此值為偶數時則除以 2,奇數則進行減 1,經過多少次處理後才會為 1,將次數回傳。

var count = 0;
var numberOfSteps = function(num) {
  if(num === 0) return 0
  else if(num === 1) return 1
  else return 1 + numberOfSteps( num % 2 !== 0 ? num - 1 : Math.floor(num/2) )
};

理解完題目的需求後,腦海則是馬上浮現出了「遞迴」,所以此題就以遞迴的方式來進行解題。


上一篇
今年我想陪著 30 天之 5
下一篇
今年我想陪著 30 天之 7
系列文
今年我想陪著 30 天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言